package com.ajx.cube.module.login;

import android.util.Log;
import android.widget.EditText;

import com.ajx.core.net.rest.CubeRest;
import com.ajx.core.net.rest.exception.ApiException;
import com.ajx.core.net.rest.observer.HttpObserver;
import com.ajx.cube.R;
import com.ajx.cube.common.mvp.DataModel;
import com.ajx.cube.common.mvp.UserDataModel;
import com.ajx.cube.base.BasePresenter;
import com.ajx.cube.util.FormUtil;

import java.util.HashMap;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * Created by lai on 2017/12/11.
 */

public class LoginPresenter extends BasePresenter<ILoginView,LoginActivity>{
    private static final String TAG = "LoginPresenter";
    public LoginPresenter(ILoginView view, LoginActivity activity) {
        super(view, activity);
    }

    public void login(EditText email, EditText password) {
        /*表单验证*/
        final String account = FormUtil.getInputTextTrim(email);
        String pwd = FormUtil.getInputTextTrim(password);
        if (account.isEmpty()){
            email.setError(getActivity().getString(R.string.error_invalid_account));
            return;
        }
        if (pwd.isEmpty()){
            password.setError(getActivity().getString(R.string.error_invalid_password));
            return;
        }
        /*参数*/
        HashMap<Object, Object> requestMap = new HashMap<>();
        requestMap.put("phone",account);
        requestMap.put("password",pwd);
        /*observable*/
        Observable login = DataModel.request(UserDataModel.class.getName())
                .params(requestMap)
                .lifecycleProvider(getActivity())
                .execute("login");
        /*observer*/
        HttpObserver<Object> observer = new HttpObserver<Object>() {
            @Override
            public void onError(ApiException e) {
                getView().closeLoading();
                getView().showMessage(e.getMsg());
                Log.e(TAG, "onError: " + e.getMsg());
            }

            @Override
            protected void onStart(Disposable d) {
                getView().showLoading();
            }

            @Override
            protected void onSuccess(Object response) {
                getView().onLogin((String) response);
                getView().closeLoading();
            }


            @Override
            public void onComplete() {
                getView().closeLoading();
            }
        };
        /*关联订阅*/
        CubeRest.toSubscribe(login,observer);

    }
}
